/* eslint-disable @typescript-eslint/no-unused-expressions */
/**
 * @description 用户
 * @author 三咲问道
 * @date 2025/7/15
 */

import { useEffect, useState } from "react";
import styles from "./GoodsIndex.module.less";
import { useGoodsStore } from "@/stores/goodsStore";

import { Table, Input, Button, Modal, Form } from "antd";
import type { TableColumnsType } from "antd";
import type { GoodsItem, GoodsStore } from "@/types/goods";

function GoodsIndex() {
  const { goodsData, getGoods, createGoods, updateGoods, deleteGoods } =
    useGoodsStore() as GoodsStore;

  /**  表格的类型 */
  interface DataType {
    key: React.Key;
    productId: string;
    productName: string;
    quantity: string;
    price: string;
    operate: unknown;
  }

  const columns: TableColumnsType<DataType> = [
    {
      title: "产品ID",
      dataIndex: "productId",
      key: "productId",
      align: "center",
    },
    {
      title: "产品名称",
      dataIndex: "productName",
      key: "productName",
      align: "center",
    },
    {
      title: "产品数量",
      dataIndex: "quantity",
      key: "quantity",
      align: "center",
    },
    {
      title: "产品价格",
      dataIndex: "price",
      key: "price",
      align: "center",
    },

    {
      title: "操作",
      dataIndex: "operate",
      key: "operate",
      align: "center",
      render: (_, record) => (
        <div className={styles["operate-content"]}>
          <div className={styles["col-1"]} onClick={() => addHandle()}>
            新增
          </div>
          <div className={styles["col-2"]} onClick={() => deleteHandle(record)}>
            删除
          </div>
          <div className={styles["col-1"]} onClick={() => updateHandle(record)}>
            修改
          </div>
        </div>
      ),
    },
  ];

  type FieldType = {
    productId?: string;
    productName?: string;
    quantity?: string;
    price?: string;
  };

  const [goodsOpen, setGoodsOpen] = useState(false);
  const [basicForm] = Form.useForm();
  const [title, setTitle] = useState<string>("新增");
  const [productId, setProductId] = useState("");

  /**  新增 */
  const addHandle = () => {
    setTitle("新增");
    setGoodsOpen(true);
  };

  /**  删除 */
  const deleteHandle = (row: GoodsItem) => {
    Modal.confirm({
      title: "删除",
      content: "您是否要删除该数据",
      onOk: async () => {
        const { productId } = row;
        const { code } = await deleteGoods({ productId });

        !code && getGoodsHandle();
      },
    });
  };

  /**  编辑 */
  const updateHandle = (row: GoodsItem) => {
    const { productId, productName, quantity, price } = row;
    setProductId(productId);
    basicForm.setFieldsValue({ productName, quantity, price });
    setTitle("编辑");
    setGoodsOpen(true);
  };

  /**  确认 */
  const handleOk = async () => {
    const formParams = basicForm.getFieldsValue();
    let res = -1;

    if (productId) {
      /**  修改 */
      const { code } = await updateGoods({ ...formParams, productId });
      res = code;
    } else {
      /**  新增 */
      const { code } = await createGoods(formParams);
      res = code;
    }

    if (res === 0) {
      handleCancel();
      getGoodsHandle();
    }
  };

  /**  取消 */
  const handleCancel = () => {
    setGoodsOpen(false);
    basicForm.setFieldsValue({ productName: "", quantity: "", price: "" });
    setProductId("");
  };

  const [searchParams, setSearchParams] = useState({
    productId: "",
    productName: "",
    quantity: "",
    price: "",
  });
  
  const [resetStatus, setResetStatus] = useState(false);

  const getGoodsHandle = (page = { pageCurrent: 1, pageSize: 10 }) => {
    getGoods({ ...searchParams, ...page });
  };

  const searchHandle = () => {
    getGoodsHandle();
  };

  const resetHandle = () => {
    setSearchParams({
      productId: "",
      productName: "",
      quantity: "",
      price: "",
    });

    setResetStatus(true);
  };

  useEffect(() => {
    if (resetStatus) {
      getGoodsHandle();
      setResetStatus(false);
    }
  }, [resetStatus]);

  const pageChange = (pageCurrent: number, pageSize: number) => {
    getGoodsHandle({ pageCurrent, pageSize });
  };

  useEffect(() => {
    getGoodsHandle();
  }, []);

  return (
    <div className={styles.contain}>
      <div className={styles["search-contain"]}>
        <div className={styles["item"]}>
          <div className={styles["name"]}>用户ID</div>
          <div className={styles["info"]}>
            <Input
              value={searchParams.productId}
              style={{ width: "200px" }}
              onChange={(e) =>
                setSearchParams({ ...searchParams, productId: e.target.value })
              }
              placeholder="请输入"
            />
          </div>
        </div>
        <div className={styles["item"]}>
          <div className={styles["name"]}>产品名称</div>
          <div className={styles["info"]}>
            <Input
              value={searchParams.productName}
              style={{ width: "200px" }}
              onChange={(e) =>
                setSearchParams({
                  ...searchParams,
                  productName: e.target.value,
                })
              }
              placeholder="请输入"
            />
          </div>
        </div>
        <div className={styles["item"]}>
          <div className={styles["name"]}>产品数量</div>
          <div className={styles["info"]}>
            <Input
              value={searchParams.quantity}
              style={{ width: "200px" }}
              onChange={(e) =>
                setSearchParams({ ...searchParams, quantity: e.target.value })
              }
              placeholder="请输入"
            />
          </div>
        </div>
        <div className={styles["item"]}>
          <div className={styles["name"]}>产品价格</div>
          <div className={styles["info"]}>
            <Input
              value={searchParams.price}
              style={{ width: "200px" }}
              onChange={(e) =>
                setSearchParams({ ...searchParams, price: e.target.value })
              }
              placeholder="请输入"
            />
          </div>
        </div>
        <div className={styles["name"]}>
          <Button
            color="primary"
            variant="solid"
            onClick={searchHandle}
            style={{ marginRight: "14px" }}
          >
            搜索
          </Button>
          <Button color="primary" variant="outlined" onClick={resetHandle}>
            重置
          </Button>
        </div>
      </div>

      <Table<DataType>
        rowKey="productId"
        columns={columns}
        dataSource={goodsData.data}
        bordered
        pagination={{
          total: goodsData.total,
          current: goodsData.pageCurrent,
          pageSize: goodsData.pageSize,
          onChange: pageChange,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />

      {/*  编辑 和 新增 */}
      <Modal
        title={title}
        open={goodsOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          form={basicForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="产品名称"
            name="productName"
            rules={[{ required: true, message: "请输入产品名称!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="产品数量" name="quantity">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="产品价格" name="price">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default GoodsIndex;
